package com.ruoyi.framework.manager.factory;

import java.util.*;
import java.util.Timer;

import com.ruoyi.common.constant.ProjectConstants;
import com.ruoyi.system.domain.SysExperts;
import com.ruoyi.system.domain.SysProjectInfo;
import com.ruoyi.system.service.*;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysOperLog;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.scheduler.Scheduler;

import javax.swing.*;

/**
 * 异步工厂（产生任务用）
 * 
 * @author ruoyi
 */
public class AsyncFactory
{
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    @Autowired
    private Scheduler scheduler;

    /**
     * 记录登录信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
            final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask()
        {
            @Override
            public void run()
            {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
                {
                    logininfor.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     * 
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    /**
     * 预评估
     *
     * @param sysProjectInfo 项目信息
     * @return 任务task
     */
    public static TimerTask processApplicate(final SysProjectInfo sysProjectInfo)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                if (!passEvaluation(sysProjectInfo)) {
                    //评估未通过，设置为未提交
                    sysProjectInfo.setState(ProjectConstants.STATE_UNCOMMITED);
                    SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                }
                else {
                    // 通过预评估
                    sysProjectInfo.setStage(ProjectConstants.STAGE_TO_ASSIGN_EXPERT);
                    SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                    //分配专家
                    if (assignExpert(sysProjectInfo, ProjectConstants.TYPE_REVIEW)) {
                        sysProjectInfo.setStage(ProjectConstants.STAGE_TO_REVIEW);
                        SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                    }
                    //剩余数量不够，则创建定时任务调用
                    else {
                        scheduleAssign(sysProjectInfo, ProjectConstants.TYPE_REVIEW, ProjectConstants.STAGE_TO_REVIEW);
                    }
                }
            }
        };
    }

    //处理验收逻辑
    public static TimerTask processAccpet(SysProjectInfo sysProjectInfo) {
        return new TimerTask() {
            @Override
            public void run() {
                //待分配专家
                sysProjectInfo.setStage(ProjectConstants.STAGE_TO_ASSIGN_ACCEPT);
                SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                //成功分配专家
                if (assignExpert(sysProjectInfo, ProjectConstants.TYPE_ACCEPT)) {
                    sysProjectInfo.setStage(ProjectConstants.STAGE_TO_EXPERT_ACCEPT);
                    SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                }
                else {
                    scheduleAssign(sysProjectInfo, ProjectConstants.TYPE_ACCEPT, ProjectConstants.STAGE_TO_EXPERT_ACCEPT);
                }
            }
        };
    }

    private static void scheduleAssign(SysProjectInfo sysProjectInfo, Long type, Long nextStage) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (assignExpert(sysProjectInfo, type)) {
                    sysProjectInfo.setStage(nextStage);
                    SpringUtils.getBean(ISysProjectInfoService.class).updateSysProjectInfo(sysProjectInfo);
                    //关闭定时器
                    timer.cancel();
                }
            }
        }, new Date(), ProjectConstants.TIME_HALF_DAY); //调试使用，应用TIME_HALF_DAY
    }
    //评估算法
    private static boolean passEvaluation (SysProjectInfo sysProjectInfo) {
        return true;
    }

    //专家分配算法
    private static boolean assignExpert (SysProjectInfo sysProjectInfo, Long type) {
        SysExperts sysExperts = new SysExperts();
        sysExperts.setDirection(sysProjectInfo.getDirection());
        sysExperts.setCurReviewCount(ProjectConstants.MAX_REVIEW_COUNT);
        //查询列表
        List<SysExperts> sysExpertsList = SpringUtils.getBean(ISysExpertsService.class).selectSysExpertsList(sysExperts);
        if (sysExpertsList == null || sysExpertsList.size() == 0) return false;
        //获取当前方向审批数最少的专家
        sysExpertsList.sort((o1, o2) -> (int) (o1.getCurReviewCount() - o2.getCurReviewCount()));
        SysExperts expert = sysExpertsList.get(0);
        //更新专家信息
        expert.setCurReviewCount(expert.getCurReviewCount() + 1);
        SpringUtils.getBean(ISysExpertsService.class).updateSysExperts(expert);
        //更新项目专家信息
        sysProjectInfo.setReviewer(expert.getName());
        //创建项目专家映射内容
        return SpringUtils.getBean(ISysProjectExpertService.class).buildProjectExpert(expert, sysProjectInfo, type) > 0;
    }
}
